
<template>
  <el-dialog :close-on-click-modal="false"
             title="编辑合作单位"
             v-dialogDrag
             :visible.sync="formVisible"
             center
             width="60%"
             :before-close="handleClose"
             >

     <form-assembly-new
       ref="formAssemblyNewRef"
        :entryFrom="entryFrom"
        @makeSure="doUpdate"
        @cancel="closeDialog"
    >
    </form-assembly-new>

  </el-dialog>
</template>



<script>
import partnerApi from '@/api/platformJiaojianyi/partner'
import FormAssemblyNew from '@/components/FormAssemblyNew'
import specialAttr from '@/utils/special-attr'

export default {
  name: 'PartnerEdit',
  components: {
    FormAssemblyNew
  },
  data() {
    return {
      entryFrom: 'edit',//入口，add(新增),edit(编辑)，判断是从‘新增’进入，还是从‘编辑’进入，必填
      parentId: '0',
      formObj: {},
      // 动态表单
      dynFormData:{
        formData:{},
      },
      rowItem: {},
      subTable: {},
options: {

 },
      formVisible: false,
    }
  },
   async created() {

       // 初始化数据
    this.initApi()
  },
  methods: {
    async initApi () {
      let str = 'insertFormData'//新增编辑展示显示的formdata
      if(this.entryFrom === 'add' || !this.entryFrom){
        str = 'insertFormData'
      }else if(this.entryFrom === 'edit'){
        str = 'updateFormData'
      }else if(this.entryFrom === 'show'){
        str = 'detailFormData'
      }
      let objDatas = [];
      let code = sessionStorage.getItem('routerCode');
      let menus = JSON.parse(sessionStorage.getItem('routerMenus'));
      if(menus!=null){
        menus.forEach((item) => {
          if(item.menuCode==code){
            objDatas.push(item)
          }
        })
      }
      let menusOne = JSON.parse(JSON.stringify(objDatas[0]))
      let formObj = JSON.parse(JSON.stringify(menusOne))
      for (let i = 0; i <  formObj[str].elements.length; i ++) {
          let obj = formObj[str].elements[i];
          // URL
          if (obj.fieldDataType && obj.fieldDataType == 2) {
            let {url, label, value} = obj.dataSources[0];
            let {data} = await partnerApi.dataApi({url, label, value}) || {}
            this.options[obj.webEntityData] = data;
          } 
          // 静态字符串
          else if (obj.fieldDataType && obj.fieldDataType == 4) {
            let json = obj.dataJson;
            this.options[obj.webEntityData] = JSON.parse(json)
          }
          // 外键
          else if (obj.fieldDataType && (obj.fieldDataType == 3 || obj.fieldDataType == 5)) {
            
            await this['get' + obj.foreignDataClassName + 'Api'](obj.mainFieldLabelName)
          }
      }
    },

    /**
     * 打开编辑表单
     */
    handleUpdate(row, menusOne) {
      let str = 'insertFormData'//新增编辑展示显示的formdata
      if(this.entryFrom === 'add' || !this.entryFrom){
        str = 'insertFormData'
      }else if(this.entryFrom === 'edit'){
        str = 'updateFormData'
      }else if(this.entryFrom === 'show'){
        str = 'detailFormData'
      }
      partnerApi.get(row.id).then(res=>{
        if(res.code === '000000'){
          if(res.data){            
            this.rowItem = JSON.parse(JSON.stringify(res.data))
            this.formObj = JSON.parse(JSON.stringify(menusOne))
            if(this.rowItem){
              this.parentId = this.rowItem.parentId
            } else {
              this.parentId = '0'
            }
            //获取字典项
            let dictionaryEntry = JSON.parse(sessionStorage.getItem('constCode'))
            if(!dictionaryEntry){
              dictionaryEntry = []
            }
            // let applicationEntry = JSON.parse(localStorage.getItem('applications'))
            let applicationEntry = JSON.parse(sessionStorage.getItem('userinfos')).applications

            let applicationCode;
            for (let i = 0; i < applicationEntry.length; i++) {
              let item = applicationEntry[i];
              if (this.formObj.appId === item.id) {
                applicationCode = item.code;
                break;
              }
            }

            
          this.formObj[str].elements.forEach((item,index)=>{
              // 组装枚举数据
              if(item.fieldSpecialType === specialAttr.fieldSpecialType.ENUM_TYPE.code){
                item.options = []
                dictionaryEntry.forEach((item1,index1) => {
                  if(item1.constCode == item.dicTypeData){
                    item.options.push({ label: item1.name, value: item1.value })
                  }
                })
              // 组装外键数据
              }else if(item.fieldSpecialType === specialAttr.fieldSpecialType.FK_TYPE.code){
                item.options = this.options[item.foreignData]
              // 组装多对多数据
              }else if(item.fieldSpecialType === specialAttr.fieldSpecialType.MTM_TYPE.code){
                item.options = this.options[item.webEntityData]
              // 组装其他数据
              }else if(item.fieldSpecialType === specialAttr.fieldSpecialType.OTHER_WEB.code){
                item.options = this.options[item.webEntityData]
              }
              // 回显的value值
              if(this.formObj.elementGroups && this.formObj.elementGroups.length>0){
                this.formObj.elementGroups.forEach((item1,index1)=>{
                  if(item.groupIdentity === item1.identifying){
                    // 主表回显
                    if(item1.isBase){
                      if(this.rowItem.hasOwnProperty(item.prop)){
                        item.value = this.rowItem[item.prop]
                      }
                      let extension = this.rowItem['extension']?JSON.parse(this.rowItem['extension']):{}
                      if(item.isExtend){
                        item.value = extension[item.prop]
                      }
                    }
                    // 扩展表的回显
                    if(item1.isSubExtend){
                      if(this.rowItem[item1.attributeName].hasOwnProperty(item.prop)){
                        item.value = this.rowItem[item1.attributeName][item.prop]
                      }
                    }
                    // 地理信息组件的回显
                    if(item.editType==='gic'){
                      item.value = {
                        province: this.rowItem.province,
                        city: this.rowItem.city,
                        area: this.rowItem.area,
                        street: this.rowItem.street,
                        address: this.rowItem.address,
                        longitude: this.rowItem.longitude,
                        latitude: this.rowItem.latitude,
                        type: JSON.parse(item.dataJson).type.toString()
                      }
                    }
                    
                  }
                })
              }
              // isParentId 代表是tree表
              if(item.isParentId){
                item.options = treeOptions
              }
              //编码规则校验
              if(item.isSerialNumber==true){
                item.disabled = true
                item.isCustomValue = true
              }
            })
            let subTable = {}
            if(this.formObj.elementGroups && this.formObj.elementGroups.length>0){
              this.formObj.elementGroups.forEach((item1,index1)=>{
                if(item1.isSub){
                  if(this.entryFrom === 'edit'){
                    subTable[item1.attributeName + "List"] = this.rowItem[item1.attributeName + "List"]
                  }
                }      
                
              })
            }
            this.$set(this.formObj,'subTable',subTable)
            this.formVisible = true
            this.$nextTick(()=>{
              this.$refs.formAssemblyNewRef.handleAsseData(this.formObj,str)
            })
          
          }
        }else {
          this.$message.error(res.message);
        }
      })
    },
    /**
     * 执行修改操作
     */
    doUpdate(form) {
      form.parentId = this.parentId;
      let args = Object.assign({id: this.rowItem.id}, form)
      partnerApi.update(args)
        .then(res => {
          if (res.code === '000000') {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.$emit('updated')
            this.$refs.formAssemblyNewRef.handleCancelForm()
            this.formVisible = false
          }else{
             this.$message({
             type: 'error',
             message: res.message
            })
          }
        })
    },
    // 子组件点击取消按钮让dialog的formVisible:false;
    closeDialog(){
      this.formVisible = false;
    },
    // 点击右上角的关闭按钮时让form表单置空
    handleClose(done){
      this.$refs.formAssemblyNewRef.handleCancelForm()
      done();
    }
  }
}
</script>
